﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LifeTree.Core;
using LifeTree.Core.Utils;
using LifeTree.DomainModel.Repositories;
using LifeTree.EntityFrameworkProvider.Repositories;
using LifeTree.Core.DataAccess;

namespace LifeTree.EntityFrameworkProvider
{
    public class UnitOfWork : DisposableResource, IUnitOfWork
    {
        private bool disposed = false;

        private readonly LifeTreeContext dataContext;

        private IWorkbookRepository workbookRepository;

        private ITaskRepository taskRepository;


        public UnitOfWork(IDatabaseFactory factory)
            : this(factory.Create())
        {

        }

        public UnitOfWork(LifeTreeContext dataContext)
        {
            this.dataContext = dataContext;
        }

        protected override void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    dataContext.Dispose();
                }
            }
            this.disposed = true;
        }

        public IWorkbookRepository WorkbookRepository
        {
            get
            {
                if (workbookRepository == null)
                    workbookRepository = new WorkbookRepository(this.dataContext);

                return workbookRepository;
            }
        }

        public ITaskRepository TaskRepository
        {
            get
            {
                if (taskRepository == null)
                    taskRepository = new TaskRepository(this.dataContext);

                return taskRepository;
            }
        }

        public void SaveChanges()
        {
            this.dataContext.SaveChanges();
        }
    }
}
